import json
import os

import pymysql
from flask import Flask, request, jsonify, render_template
import time
import re
from utils.func_utils import RequestUtils, DBUtils

app = Flask(__name__)


class TestCommand:
    def __init__(self, env):
        self.env = env
        self.headers = {
            "accept": "application/json, text/plain, */*",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "zh-CN, zh;q=0.9",
            "content-type": "application/json;charset=UTF-8"
        }

    def get_logs_query(self, ecu, time_linetypes=None, cmd=None, number=None, start_time=None, end_time=None):
        """
        获取日志查询
        :param time_linetypes: 日志类型，枚举值：CMD、GPS、BMS、BATTERY、WIFI、BLE、ALARM、STATUS、EVENT、OTHER
        :param cmd: 指令
        :param number: 日志条数
        :param start_time: 开始时间
        :param ecu: ECU编号
        :return:
        """
        # start_time = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.localtime(time.time() - 20 * 60 * 60))
        # end_time = time.strftime("%Y-%m-%dT%H:%M:%S.998Z", time.localtime(time.time() - 10 * 60 * 60))
        start_time = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.strptime(start_time, "%Y-%m-%d %H:%M:%S"))
        end_time = time.strftime("%Y-%m-%dT%H:%M:%S.998Z", time.strptime(end_time, "%Y-%m-%d %H:%M:%S"))
        if cmd is None:
            cmd = ""
        query = {
            "params": {
                "page_size": "1000",
                "bike_sn": "",
                "ecu_sn": ecu,
                "cmd": cmd,
                "cmd_code": "",
                "timeline_start_time": start_time,
                "timeline_end_time": end_time,
                "time_linetypes": [time_linetypes] if time_linetypes is not None else [],
                "scroll_id": "",
                "gsm_signal_strength": "",
                "standby_battery_capacity": "",
                "parse_able": True
            }
        }
        print("传入参数")
        print(query)
        datas = json.dumps(query)
        url = "http://test-os-gateway.songguo7.com/api/iot-timeline/timeline/list"
        headers = DBUtils().get_headers("test")
        # response = requests.post(url=url, data=datas, headers=headers, timeout=None)
        response = RequestUtils().all_request(method="post", url=url, data=datas, headers=headers, timeout=None)
        data = response.json()
        if "error" in data.keys():
            headers = DBUtils().update_headers("test")
            response = RequestUtils().all_request(method="post", url=url, data=datas, headers=headers, timeout=None)
            # response = requests.post(url=url, data=datas, headers=headers, timeout=None)
            data = response.json()["data"]
            time_line_record_list = data["time_line_record_entities"]
            print(time_line_record_list)
            if number is None:
                return time_line_record_list[0]
            else:
                return time_line_record_list
        else:
            data = data["data"]
            time_line_record_list = data["time_line_record_entities"]
            print("结果")
            print(time_line_record_list)
            try:
                items = dict()
                print(len(time_line_record_list))
                with open(os.path.join(os.getcwd(), f"datas/time_line_record_{ecu}_{start_time}_{end_time}_{cmd}.json"),
                          "w") as f:
                    f.write(json.dumps(time_line_record_list, indent=4, ensure_ascii=False))
            except:
                items = dict()

            if number is None:
                try:
                    return time_line_record_list[0]
                except:
                    print("here has a error!")
            else:
                return time_line_record_list

    def get_ota_template_list(self):
        # 假设这是一个获取OTA模板列表的方法
        return [
            {"template_id": "1", "product_name": "ProductA", "template_name": "Template_1.0_2.0",
             "package_type": "MCU_PACKAGE", "mcu_upgrade_msg": "MCU_1.0", "template_state": "USEING"},
            {"template_id": "2", "product_name": "ProductA", "template_name": "Template_2.0_1.0",
             "package_type": "MCU_PACKAGE", "mcu_upgrade_msg": "MCU_2.0", "template_state": "USEING"},
            # 其他模板...
        ]

    def create_ota_task(self, ecu_list, product_name, hw_version, package_type, current_version, target_version,
                        mcu_version=None, times=1):
        """
        功能：在iov平台创建OTA升级任务
        :param ecu_list: ecu_sn列表
        :param product_name: 产品名称
        :param hw_version: 硬件版本
        :param package_type: 包类型
        :param current_version: 当前版本
        :param target_version: 目标版本
        :param mcu_version: MCU版本（可选）
        :param times: 创建任务的次数（默认1次）
        """
        template_id = ""
        description = ""
        ota_template_id = ""
        re_ota_template_id = ""

        for ota_template in self.get_ota_template_list():
            t_product_name = ota_template["product_name"]
            t_hw_version = re.search(r'.*?_(.*?)_', ota_template["template_name"]).group(1)
            t_package_type = ota_template["package_type"]
            t_current_version = re.search(r'.*\"(.*?)\"', ota_template["template_name"]).group(1)
            t_target_version = re.search(r'.*_(.*)', ota_template["template_name"]).group(1)
            t_mcu_version = re.search(r'.*?\"(.*?)\"', ota_template["mcu_upgrade_msg"]).group(1)
            t_status = ota_template["template_state"]

            if package_type == "MCU_PACKAGE":
                if (t_product_name == product_name and t_hw_version == hw_version and
                        t_package_type == package_type and t_current_version == current_version and
                        t_target_version == target_version and t_status == "USEING"):
                    ota_template_id = ota_template["template_id"]
                    print("找到ota upgrade模板：", ota_template_id)
                elif (t_product_name == product_name and t_hw_version == hw_version and
                      t_package_type == package_type and t_current_version == target_version and
                      t_target_version == current_version and t_status == "USEING"):
                    re_ota_template_id = ota_template["template_id"]
                    print("找到re ota upgrade模板：", re_ota_template_id)
            else:
                if mcu_version is None:
                    print("配件升级时，必须指定mcu_version！")
                    return
                else:
                    if (t_product_name == product_name and t_hw_version == hw_version and
                            t_package_type == package_type and t_current_version == current_version and
                            t_target_version == target_version and t_mcu_version == mcu_version and t_status == "USEING"):
                        ota_template_id = ota_template["template_id"]
                        print("找到ota upgrade模板：", ota_template_id)
                    elif (t_product_name == product_name and t_hw_version == hw_version and
                          t_package_type == package_type and t_current_version == target_version and
                          t_target_version == current_version and t_mcu_version == mcu_version and t_status == "USEING"):
                        re_ota_template_id = ota_template["template_id"]
                        print("找到re ota upgrade模板：", re_ota_template_id)

        for i in range(times):
            if i % 2 == 0:
                template_id = ota_template_id
                description = f"{product_name} {package_type} {current_version} -> {target_version}"
            elif i % 2 == 1:
                template_id = re_ota_template_id
                description = f"{product_name} {package_type} {target_version} -> {current_version}"
            print(">>> template_id:", template_id)
            print(">>> description:", description)
            params = {
                "params": {
                    "task_start_time": int(time.time() * 1000),
                    "task_end_time": int(time.time() * 1000) + (20 * 60 * 1000),
                    "description": description,
                    "ecu_filter": {},
                    "ste_sns": ecu_list,
                    "task_type": "OTA_UPGRADE",
                    "template_id": template_id
                }
            }

            url = ""
            if self.env == "test":
                url = "https://test-techgw.songguo7.com/iot-admin/arc/task/create"
            elif self.env == "online":
                url = "https://techgw.songguo7.com/iot-admin/arc/task/create"

            res = RequestUtils().all_request(url=url, method="post", json=params, headers=self.headers)
            if "error" in res.text:
                print("create ota task failed")
                db = pymysql.connect(host="localhost", port=3306, user='root', password='00000000', db='testdb')
                cursor = db.cursor()
                for ecu in ecu_list:
                    sql = f"insert into ota_records values (null, {ecu}, 'fail', '{description}', default)"
                    cursor.execute(sql)
                    data = cursor.fetchall()
                    db.commit()
                db.close()
                cursor.close()
                return 
            else:
                print(f"create ota task success and upgrade {i + 1} times success")
                time.sleep(20 * 60)
                vv = description.split(' ')[-1]
                for ecu in ecu_list:
                    if f'"MCU版本号: 0x10":"{vv}"' in self.get_logs_query(ecu, cmd=1):
                        db = pymysql.connect(host="localhost", port=3306, user='root', password='00000000', db='testdb')
                        cursor = db.cursor()
                        for ecu in ecu_list:
                            sql = f"insert into ota_records values (null, {ecu}, 'success', '{description}', default)"
                            cursor.execute(sql)
                            data = cursor.fetchall()
                            db.commit()
                        db.close()
                        cursor.close()
                return 


# 路由：显示表单页面
@app.route('/create_ota_task', methods=['GET'])
def create_ota_task_form():
    pkg_type_dict = {
        "控制器包": "CONTROLLER_PACKAGE",
        "固件包": "MCU_PACKAGE"
    }
    hw_version_list = ["2.1.0", "2.1.1", "3.1.0", "4.1.0"]
    pkg_type_list = list(pkg_type_dict.keys())

    return render_template('create_ota_task_form.html', pkg_type_dict=pkg_type_dict, hw_version_list=hw_version_list)


# 路由：处理表单提交
@app.route('/create_ota_task', methods=['POST'])
def create_ota_task_submit():
    ecu_list = request.form.getlist('ecu_sn')
    product_name = request.form.get('product_name')
    hw_version = request.form.get('hw_version')
    package_type = request.form.get('package_type')
    current_version = request.form.get('current_version')
    target_version = request.form.get('target_version')
    mcu_version = request.form.get('mcu_version')
    times = int(request.form.get('times', 1))

    test_command = TestCommand(env="test")  # 设置环境为test
    result = test_command.create_ota_task(
        ecu_list=ecu_list,
        product_name=product_name,
        hw_version=hw_version,
        package_type=package_type,
        current_version=current_version,
        target_version=target_version,
        mcu_version=mcu_version,
        times=times
    )

    return jsonify({"result": result})


if __name__ == '__main__':
    app.run(debug=True)
